package com.ssm_basic.egweibo2.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.ssm_basic.egweibo2.base.response.JsonResult;
import com.ssm_basic.egweibo2.base.utils.CacheUtils;
import com.ssm_basic.egweibo2.mapper.WeiboMapper;
import com.ssm_basic.egweibo2.pojo.dto.WeiboAddParam;
import com.ssm_basic.egweibo2.pojo.entity.Weibo;
import com.ssm_basic.egweibo2.pojo.vo.UserVO;
import com.ssm_basic.egweibo2.pojo.vo.WeiboDetailVO;
import com.ssm_basic.egweibo2.pojo.vo.WeiboIndexVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Api(tags = "2.微博模块")
@Validated
@Slf4j
@RestController
@RequestMapping("/v1/weibo/")
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;
    @Autowired
    private CacheUtils cacheUtils;

    @ApiOperation("发布微博")
    @ApiOperationSupport(order = 5)
    @PostMapping("publish")
    public JsonResult  publish(@RequestBody WeiboAddParam content, @ApiIgnore HttpSession session) {
        log.debug("content:{}", content);
        UserVO  user = (UserVO) session.getAttribute("user");
        Weibo weibo = new Weibo();
        weibo.setContent(content.getContent());
        weibo.setUserId(user.getId());
        weibo.setCreated(new Date());
        weiboMapper.insert(weibo);
        return JsonResult.success();
    }

    @ApiOperation("微博首页列表")
    @ApiOperationSupport(order = 10)
    @GetMapping("selectIndex")
    public JsonResult selectIndex() {
        Serializable weiboIndex = cacheUtils.get("weibo_index");
        if (weiboIndex != null) {
            return JsonResult.success(weiboIndex);
        }
        List<WeiboIndexVO> list = weiboMapper.selectIndex();
        cacheUtils.setExpire("weibo_index", (Serializable) list, 10, TimeUnit.MINUTES);
        return JsonResult.success(list);
    }

    @ApiOperation("微博详情页")
    @ApiOperationSupport(order = 15)
    @GetMapping("selectById")
    public JsonResult selectById(@Range(min = 1, max =100, message = "微博的编号id必须在1-100之间") @RequestParam Long id) {
        log.debug("id:{}", id);
        WeiboDetailVO weiboDetailVO = weiboMapper.selectDetail(id);
        return JsonResult.success(weiboDetailVO);
    }

}
